#include "stdafx.h"
#include "math.h"
#include "PolyMesh.h"

PolyMesh::PolyMesh()
{
	vertexN = 0;
	faceN = 0;
	vertex = NULL;
	face = NULL;
	normal_f = NULL;
}

PolyMesh::~PolyMesh()
{
	if(vertex != NULL)
		delete[] vertex;
	if(face != NULL)
		delete[] face;
	if(normal_f != NULL)
		delete[] normal_f;
}

void PolyMesh::setSize(int _vertexN,int _faceN)
{
	vertexN = _vertexN;
	faceN = _faceN;
	vertex = new float[_vertexN][3];
	face = new int[_faceN][3];
}

void PolyMesh::setVertex(int _i,float _x,float _y,float _z)
{
	vertex[_i][0] = _x;
	vertex[_i][1] = _y;
	vertex[_i][2] = _z;
}

void PolyMesh::setFace(int _i,int _i0,int _i1,int _i2)
{
	face[_i][0] = _i0;
	face[_i][1] = _i1;
	face[_i][2] = _i2;
}

void PolyMesh::computeFaceNormal()
{
	if(normal_f != NULL)
		delete[] normal_f;
	normal_f = new float[faceN][3];
	for(int i=0; i<faceN; i++)
	{
		float v1[3], v2[3];
		double n[3];
		double length;
		VEC(v1, vertex[face[i][0]], vertex[face[i][1]]);
		VEC(v2, vertex[face[i][0]], vertex[face[i][2]]);
		CROSS(n, v1, v2);
		length = LENGTH(n);
		if((float)length != 0){
			normal_f[i][0] = (float)(n[0]/length);
			normal_f[i][1] = (float)(n[1]/length);
			normal_f[i][2] = (float)(n[2]/length);
		}
		else
			normal_f[i][0] = normal_f[i][1] = normal_f[i][2] = 0.0f;
	}
}

void PolyMesh::VEC(float _v[3], float _p1[3], float _p2[3])
{
	_v[0] = _p2[0]-_p1[0];
	_v[1] = _p2[1]-_p1[1];
	_v[2] = _p2[2]-_p1[2];
}

void PolyMesh::CROSS(double _n[3], float _v1[3], float _v2[3])
{
	_n[0] = (double)_v1[1]*(double)_v2[2] - (double)_v1[2]*(double)_v2[1];
	_n[1] = (double)_v1[2]*(double)_v2[0] - (double)_v1[0]*(double)_v2[2];
	_n[2] = (double)_v1[0]*(double)_v2[1] - (double)_v1[1]*(double)_v2[0];
}

double PolyMesh::LENGTH(double v[3])
{
	return sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
}